//Observer（观察者模式）
//Observer模式定义了一种一对多的依赖关系，使得当一个对象状态改变时，它的所有依赖者都会收到通知并自动更新。在Go语言中，可以使用通道和协程来实现观察者模式。

package observer

import (
	"fmt"
)

// 观察者接口
type Observer interface {
	Update(temperature, humidity float64)
}

// 目标接口
type Subject interface {
	RegisterObserver(o Observer)
	RemoveObserver(o Observer)
	NotifyObservers()
}

// 气象站，目标
type WeatherStation struct {
	observers []Observer
}

func (ws *WeatherStation) RegisterObserver(o Observer) {
	ws.observers = append(ws.observers, o)
}

func (ws *WeatherStation) RemoveObserver(o Observer) {
	for i, obs := range ws.observers {
		if obs == o {
			ws.observers = append(ws.observers[:i], ws.observers[i+1:]...)
		}
	}
}

func (ws *WeatherStation) NotifyObservers() {
	for _, obs := range ws.observers {
		go obs.Update(70.0, 60.0)
	}
}

// 观察者，例如天气预报应用
type WeatherApp struct{}

func (wa *WeatherApp) Update(temperature, humidity float64) {
	fmt.Printf("WeatherApp: Temperature: %v, Humidity: %v\n", temperature, humidity)
}

func demo_oberver() {
	weatherStation := &WeatherStation{}
	weatherApp := &WeatherApp{}

	weatherStation.RegisterObserver(weatherApp)
	weatherStation.NotifyObservers()
}
